﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/15 11:40:00
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary.Forms;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Windows.Forms;

namespace CommonLibrary
{
    /// <summary>
    /// Modbus管理窗体
    /// </summary>
    public partial class FormModbus : HWFrmWithTitle
    {
        private bool mIsFirstTimeSelected = true;
        private int mTcpLastSelectedRowIndex = -1;
        private int mSerialLastSelectedRowIndex = -1;
        /// <summary>
        /// 构造函数
        /// </summary>
        public FormModbus()
        {
            InitializeComponent();
        }
        private void FormModbus_Load(object sender, EventArgs e)
        {
            InitModbusColumns();
            LoadModbusConfig();
        }
        private void LoadModbusConfig()
        {
            this.mIsFirstTimeSelected = true;
            this.mSerialLastSelectedRowIndex = -1;
            this.mTcpLastSelectedRowIndex = -1;
            this.dataGridViewRtu.Rows.Clear();
            this.dataGridViewTcp.Rows.Clear();
            this.dataGridViewModules.Rows.Clear();

            var configs = ModbusHelper.GetModbusConfig();
            if (configs != null && configs.Count > 0)
            {
                var tcps = configs.FindAll(v => v.CommunicationType == ECommunicationType.MODBUS_TCP && v.TcpEntity != null);
                var rtus = configs.FindAll(v => v.CommunicationType == ECommunicationType.MODBUS_RTU && v.SerialEntity != null);
                if (tcps != null && tcps.Count > 0)
                {
                    this.dataGridViewTcp.Rows.Clear();

                    foreach (var t in tcps)
                    {
                        var index = this.dataGridViewTcp.Rows.Add(1);
                        DataGridViewRow newRow = this.dataGridViewTcp.Rows[index];
                        newRow.Cells["Name"].Value = t.Name;
                        newRow.Cells["TcpIP"].Value = t.TcpEntity.IP;
                        newRow.Cells["TcpPort"].Value = t.TcpEntity.Port;
                        newRow.Cells["Station"].Value = t.Station.ToString();
                        newRow.Cells["DataFormat"].Value = t.Format.ToString();
                        newRow.Cells["IsStringReserve"].Value = t.IsStringReserve;
                        newRow.Tag = t;
                    }
                }
                if (rtus != null && rtus.Count > 0)
                {
                    this.dataGridViewRtu.Rows.Clear();

                    foreach (var r in rtus)
                    {
                        var index = this.dataGridViewRtu.Rows.Add(1);
                        DataGridViewRow newRow = this.dataGridViewRtu.Rows[index];
                        newRow.Cells["Name"].Value = r.Name;
                        newRow.Cells["PortName"].Value = !string.IsNullOrWhiteSpace(r.SerialEntity.PortName) && PortNames.Contains(r.SerialEntity.PortName) ? r.SerialEntity.PortName : PortNames[0];
                        newRow.Cells["Parity"].Value = r.SerialEntity.ParityBit.ToString();
                        newRow.Cells["DataBit"].Value = r.SerialEntity.DataBit.ToString();
                        newRow.Cells["StopBit"].Value = r.SerialEntity.StopBit.ToString();
                        newRow.Cells["BaudRate"].Value = r.SerialEntity.BaudRate.ToString();
                        newRow.Cells["Station"].Value = r.Station.ToString();
                        newRow.Cells["DataFormat"].Value = r.Format.ToString();
                        newRow.Cells["IsStringReserve"].Value = r.IsStringReserve;
                        newRow.Tag = r;
                    }
                }
            }
            this.dataGridViewTcp.Rows[0].Cells[0].Selected = true;
        }
        private string[] PortNames = SerialPort.GetPortNames();
        DataGridViewComboBoxColumn dataFormatColumn = new DataGridViewComboBoxColumn();
        DataGridViewCheckBoxColumn isStringReserveColumn = new DataGridViewCheckBoxColumn();

        DataGridViewComboBoxColumn portNameRtuColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn baudRateRtuColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn parityRtuColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn dataBitRtuColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn stopBitRtuColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn dataFormatRtuColumn = new DataGridViewComboBoxColumn();
        DataGridViewCheckBoxColumn isStringReserveRtuColumn = new DataGridViewCheckBoxColumn();

        DataGridViewComboBoxColumn dataTypeModulesColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn targetDataTypeModulesColumn = new DataGridViewComboBoxColumn();
        DataGridViewCheckBoxColumn isNumberConvertModulesColumn = new DataGridViewCheckBoxColumn();

        private void InitModbusColumns()
        {
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Name", "名称");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TcpIP", "IP");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TcpPort", "端口");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Station", "站点");
            CommonHelper.InitComboGridColumn(dataFormatColumn, "DataFormat", "数据格式", Enum.GetNames(typeof(EDataFormat)));
            CommonHelper.InitCheckboxGridColumn(isStringReserveColumn, "IsStringReserve", "字符串反转");

            this.dataGridViewTcp.Columns.Add(dataFormatColumn);
            this.dataGridViewTcp.Columns.Add(isStringReserveColumn);
            this.dataGridViewTcp.DoubleBufferedDataGirdView(true);
            this.dataGridViewTcp.InitStyle();

            CommonHelper.CreateTextGridColumn(this.dataGridViewRtu, "Name", "名称");
            CommonHelper.InitComboGridColumn(portNameRtuColumn, "PortName", "串口", PortNames);
            CommonHelper.InitComboGridColumn(baudRateRtuColumn, "BaudRate", "波特率", new string[] { "2400", "4800", "9600", "14400", "19200", "115200" });
            CommonHelper.InitComboGridColumn(parityRtuColumn, "Parity", "校验位", new string[] { "0", "1", "2", "3", "4" });
            CommonHelper.InitComboGridColumn(dataBitRtuColumn, "DataBit", "数据位", new string[] { "5", "6", "7", "8" });
            CommonHelper.InitComboGridColumn(stopBitRtuColumn, "StopBit", "停止位", new string[] { "0", "1", "2", "3" });
            CommonHelper.InitComboGridColumn(dataFormatRtuColumn, "DataFormat", "数据格式", Enum.GetNames(typeof(EDataFormat)));
            CommonHelper.InitCheckboxGridColumn(isStringReserveRtuColumn, "IsStringReserve", "字符串反转");

            this.dataGridViewRtu.Columns.Add(portNameRtuColumn);
            this.dataGridViewRtu.Columns.Add(baudRateRtuColumn);
            this.dataGridViewRtu.Columns.Add(parityRtuColumn);
            this.dataGridViewRtu.Columns.Add(dataBitRtuColumn);
            this.dataGridViewRtu.Columns.Add(stopBitRtuColumn);
            CommonHelper.CreateTextGridColumn(this.dataGridViewRtu, "Station", "站点");
            this.dataGridViewRtu.Columns.Add(dataFormatRtuColumn);
            this.dataGridViewRtu.Columns.Add(isStringReserveRtuColumn);
            this.dataGridViewRtu.DoubleBufferedDataGirdView(true);
            this.dataGridViewRtu.InitStyle();

            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Name", "名称");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Address", "读取地址");
            CommonHelper.InitComboGridColumn(dataTypeModulesColumn, "DataType", "数据类型", Enum.GetNames(typeof(EDataType)));
            CommonHelper.InitComboGridColumn(targetDataTypeModulesColumn, "TargetDataType", "目标数据类型", Enum.GetNames(typeof(EDataType)));
            CommonHelper.InitCheckboxGridColumn(isNumberConvertModulesColumn, "IsNumberConvert", "数据转换");
            this.dataGridViewModules.Columns.Add(dataTypeModulesColumn);
            this.dataGridViewModules.Columns.Add(targetDataTypeModulesColumn);
            this.dataGridViewModules.Columns.Add(isNumberConvertModulesColumn);
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "PLCAddress", "PLC地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Remark", "备注");

            this.dataGridViewModules.DoubleBufferedDataGirdView(true);
            this.dataGridViewModules.InitStyle();
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "数据保存中，请稍候......");

            if (GlobalStatus.APP == EAppStatus.RUN)
            {
                HWMessageBox.Show(this, "设备运行中，不允许修改参数");
                CommonHelper.CloseWaiting();
                return;
            }
            try
            {
                SaveModules();
                #region tcp
                bool isValidTcp = true, isValidRtu = true;
                List<ModbusEntity> list = new List<ModbusEntity>();
                if (this.dataGridViewTcp.Rows != null && this.dataGridViewTcp.Rows.Count > 0)
                {
                    int rowIndex = 0;
                    foreach (DataGridViewRow row in this.dataGridViewTcp.Rows)
                    {
                        var name = CommonHelper.GetCellStringValue(row, "Name");
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            if (list.Find(v => v.Name.Equals(name)) != null)
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的名称有重复");
                                break;
                            }
                            var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                            var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                            var station = CommonHelper.GetCellStringValue(row, "Station");
                            var dataFormat = CommonHelper.GetCellStringValue(row, "DataFormat");
                            var isStringReserve = CommonHelper.GetCellStringValue(row, "IsStringReserve");

                            IPAddress ipValue = null;
                            if (!IPAddress.TryParse(ip, out ipValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的IP有误");
                                isValidTcp = false;
                                break;
                            }
                            int portValue = 502;
                            if (!int.TryParse(port, out portValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的端口有误");
                                isValidTcp = false;
                                break;
                            }
                            short stationValue = 1;
                            if (!short.TryParse(station, out stationValue) || stationValue <= 0 || stationValue > 255)
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的站点有误");
                                isValidTcp = false;
                                break;
                            }
                            EDataFormat dataFormatValue = CommonHelper.GetEnumByName(dataFormat, EDataFormat.CDAB);
                            bool isStringReserveValue = isStringReserve.ToUpper().Equals("TRUE") ? true : false;


                            List<ModbusPositionEntity> positionEntities = new List<ModbusPositionEntity>();
                            if (row.Tag != null && row.Tag is ModbusEntity)
                            {
                                positionEntities = (row.Tag as ModbusEntity).AddressList;
                            }
                            list.Add(new ModbusEntity()
                            {
                                CommunicationType = ECommunicationType.MODBUS_TCP,
                                Format = dataFormatValue,
                                IsStringReserve = isStringReserveValue,
                                Name = name,
                                Station = (byte)stationValue,
                                TcpEntity = new TcpEntity()
                                {
                                    IP = ipValue.ToString(),
                                    Port = portValue,
                                },
                                AddressList = positionEntities
                            });
                        }
                        rowIndex++;
                    }
                }
                #endregion
                if (isValidTcp)
                {
                    if (this.dataGridViewRtu.Rows != null && this.dataGridViewRtu.Rows.Count > 0)
                    {
                        int rowIndex = 0;
                        foreach (DataGridViewRow row in this.dataGridViewRtu.Rows)
                        {
                            var name = CommonHelper.GetCellStringValue(row, "Name");
                            if (!string.IsNullOrWhiteSpace(name))
                            {
                                if (list.Find(v => v.Name.Equals(name)) != null)
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的名称有重复");
                                    break;
                                }
                                var portName = CommonHelper.GetCellStringValue(row, "PortName");
                                var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                                var parity = CommonHelper.GetCellStringValue(row, "Parity");
                                var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                                var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                                var station = CommonHelper.GetCellStringValue(row, "Station");
                                var dataFormat = CommonHelper.GetCellStringValue(row, "DataFormat");
                                var isStringReserve = CommonHelper.GetCellStringValue(row, "IsStringReserve");

                                if (string.IsNullOrWhiteSpace(portName))
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的串口有误");
                                    isValidRtu = false;
                                    break;
                                }

                                int baudRateValue = int.Parse(baudRate);
                                int parityValue = int.Parse(parity);
                                int dataBitValue = int.Parse(dataBit);
                                int stopBitValue = int.Parse(stopBit);

                                short stationValue = 1;
                                if (!short.TryParse(station, out stationValue) || stationValue <= 0 || stationValue > 255)
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的站点有误");
                                    isValidRtu = false;
                                    break;
                                }
                                EDataFormat dataFormatValue = CommonHelper.GetEnumByName(dataFormat, EDataFormat.CDAB);
                                bool isStringReserveValue = isStringReserve.ToUpper().Equals("TRUE") ? true : false;

                                List<ModbusPositionEntity> positionEntities = new List<ModbusPositionEntity>();
                                if (row.Tag != null && row.Tag is ModbusEntity)
                                {
                                    positionEntities = (row.Tag as ModbusEntity).AddressList;
                                }


                                list.Add(new ModbusEntity()
                                {
                                    CommunicationType = ECommunicationType.MODBUS_RTU,
                                    Format = dataFormatValue,
                                    IsStringReserve = isStringReserveValue,
                                    Name = name.ToString(),
                                    Station = (byte)stationValue,
                                    SerialEntity = new SerialEntity()
                                    {
                                        BaudRate = baudRateValue,
                                        DataBit = dataBitValue,
                                        ParityBit = parityValue,
                                        PortName = portName,
                                        StopBit = stopBitValue,
                                    },
                                    AddressList = positionEntities,
                                });
                            }
                            rowIndex++;
                        }
                    }
                }

                if (isValidTcp && isValidRtu)
                {
                    ModbusHelper.SaveModbusConfig(list);
                    LogHelper.Info($"修改Modbus配置\r\n{CommonHelper.GetJsonString(list)}");
                    APPInstance.ResetModbuses();
                    APPInstance.StartModbuses();
                    this.DialogResult = DialogResult.OK;
                    HWMessageBox.Show(this, "保存成功");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                HWMessageBox.Show(this, $"发生异常：{ex.Message}");
            }
            CommonHelper.CloseWaiting();
        }

        private void dataGridViewTcp_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            var dataFormatCell = e.Row.Cells["DataFormat"] as DataGridViewComboBoxCell;
            if (dataFormatCell != null)
            {
                dataFormatCell.Value = EDataFormat.CDAB.ToString();
            }

            var isStringReserve = e.Row.Cells["IsStringReserve"] as DataGridViewCheckBoxCell;
            if (isStringReserve != null)
            {
                isStringReserve.Value = false;
            }

        }

        private void dataGridViewTcp_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex.Equals(this.dataGridViewTcp.Columns.IndexOf(dataFormatColumn)))
            {
                SendKeys.Send("{F4}");
            }
        }

        private void dataGridViewRtu_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex.Equals(this.dataGridViewRtu.Columns.IndexOf(dataFormatRtuColumn))
                || e.ColumnIndex.Equals(this.dataGridViewRtu.Columns.IndexOf(portNameRtuColumn))
                || e.ColumnIndex.Equals(this.dataGridViewRtu.Columns.IndexOf(parityRtuColumn))
                || e.ColumnIndex.Equals(this.dataGridViewRtu.Columns.IndexOf(baudRateRtuColumn))
                || e.ColumnIndex.Equals(this.dataGridViewRtu.Columns.IndexOf(dataBitRtuColumn))
                || e.ColumnIndex.Equals(this.dataGridViewRtu.Columns.IndexOf(stopBitRtuColumn)))
            {
                SendKeys.Send("{F4}");
            }
        }

        private void dataGridViewRtu_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            var dataFormatCell = e.Row.Cells["DataFormat"] as DataGridViewComboBoxCell;
            if (dataFormatCell != null)
            {
                dataFormatCell.Value = EDataFormat.ABCD.ToString();
            }
            var portNameCell = e.Row.Cells["PortName"] as DataGridViewComboBoxCell;
            if (portNameCell != null && PortNames != null && PortNames.Length > 0)
            {
                portNameCell.Value = PortNames[0];
            }
            var baudRateCell = e.Row.Cells["BaudRate"] as DataGridViewComboBoxCell;
            if (baudRateCell != null)
            {
                baudRateCell.Value = "9600";
            }
            var parityCell = e.Row.Cells["Parity"] as DataGridViewComboBoxCell;
            if (parityCell != null)
            {
                parityCell.Value = "0";
            }
            var stopBitCell = e.Row.Cells["StopBit"] as DataGridViewComboBoxCell;
            if (stopBitCell != null)
            {
                stopBitCell.Value = "1";
            }
            var dataBitCell = e.Row.Cells["DataBit"] as DataGridViewComboBoxCell;
            if (dataBitCell != null)
            {
                dataBitCell.Value = "8";
            }
            var isStringReserve = e.Row.Cells["IsStringReserve"] as DataGridViewCheckBoxCell;
            if (isStringReserve != null)
            {
                isStringReserve.Value = false;
            }
        }

        private void toolStripMenuItemRead_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "功能触发中，请稍候......");
            var cells = this.dataGridViewTcp.SelectedCells;
            if (cells != null && cells.Count > 0)
            {
                var row = this.dataGridViewTcp.Rows[cells[0].RowIndex];
                var name = CommonHelper.GetCellStringValue(row, "Name");
                if (!string.IsNullOrWhiteSpace(name))
                {
                    var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                    var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                    var station = CommonHelper.GetCellStringValue(row, "Station");
                    var dataFormat = CommonHelper.GetCellStringValue(row, "DataFormat");
                    var isStringReserve = CommonHelper.GetCellStringValue(row, "IsStringReserve");
                    IPAddress ipValue = null;
                    if (!IPAddress.TryParse(ip, out ipValue))
                    {
                        HWMessageBox.Show(this, $"IP有误");
                    }
                    else
                    {
                        int portValue = 502;
                        if (!int.TryParse(port, out portValue))
                        {
                            HWMessageBox.Show(this, $"端口有误");
                        }
                        else
                        {

                            short stationValue = 1;
                            if (!short.TryParse(station, out stationValue) || stationValue <= 0 || stationValue > 255)
                            {
                                HWMessageBox.Show(this, $"站点有误");
                            }
                            else
                            {

                                EDataFormat dataFormatValue = CommonHelper.GetEnumByName(dataFormat, EDataFormat.CDAB);
                                bool isStringReserveValue = isStringReserve.ToUpper().Equals("TRUE") ? true : false;
                                int addressValue = 0;
                                try
                                {
                                    //暂时
                                    var modbusHelper = ModbusHelper.CreateTcpModbus(name, ipValue.ToString(), portValue,
                                        (byte)stationValue, dataFormatValue, isStringReserveValue, null, false);

                                    if (modbusHelper.IsConnected)
                                    {
                                        var datas = modbusHelper.Read(addressValue, 2, EDataType.SHORT.ToString().ToLower());
                                        if (datas != null && datas.Count > 0)
                                        {
                                            HWMessageBox.Show(this, $"结果：{string.Join(",", datas)}");
                                        }
                                        else
                                        {
                                            HWMessageBox.Show(this, "通讯异常");
                                        }
                                        modbusHelper.Close();
                                    }
                                    else
                                    {
                                        HWMessageBox.Show(this, "无法连接");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                }
                            }
                        }
                    }
                }
                else
                {
                    HWMessageBox.Show(this, "名称有误");
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录");
            }
            CommonHelper.CloseWaiting();
        }

        private void toolStripMenuItemRtuRead_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "功能触发中，请稍候......");
            var cells = this.dataGridViewRtu.SelectedCells;
            if (cells != null && cells.Count > 0)
            {
                var row = this.dataGridViewRtu.Rows[cells[0].RowIndex];
                var name = CommonHelper.GetCellStringValue(row, "Name");
                if (!string.IsNullOrWhiteSpace(name))
                {
                    var portName = CommonHelper.GetCellStringValue(row, "PortName");
                    var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                    var parity = CommonHelper.GetCellStringValue(row, "Parity");
                    var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                    var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                    var station = CommonHelper.GetCellStringValue(row, "Station");
                    var dataFormat = CommonHelper.GetCellStringValue(row, "DataFormat");
                    var isStringReserve = CommonHelper.GetCellStringValue(row, "IsStringReserve");
                    var address = CommonHelper.GetCellStringValue(row, "Address");
                    var length = CommonHelper.GetCellStringValue(row, "Length");
                    var dataType = CommonHelper.GetCellStringValue(row, "DataType");

                    string portNameValue = "";
                    if (string.IsNullOrWhiteSpace(portName))
                    {
                        HWMessageBox.Show(this, $"串口有误");
                    }
                    else
                    {
                        int baudRateValue = int.Parse(baudRate);
                        int parityValue = int.Parse(parity);
                        int dataBitValue = int.Parse(dataBit);
                        int stopBitValue = int.Parse(stopBit);

                        short stationValue = 1;
                        if (!short.TryParse(station, out stationValue) || stationValue <= 0 || stationValue > 255)
                        {
                            HWMessageBox.Show(this, $"站点有误");
                        }
                        else
                        {
                            EDataFormat dataFormatValue = CommonHelper.GetEnumByName(dataFormat, EDataFormat.CDAB);
                            bool isStringReserveValue = isStringReserve.ToUpper().Equals("TRUE") ? true : false;
                            int addressValue = 0;
                            if (!int.TryParse(address, out addressValue))
                            {
                                HWMessageBox.Show(this, $"地址有误");
                            }
                            else
                            {
                                ushort lengthValue = 0;
                                if (!ushort.TryParse(length, out lengthValue))
                                {
                                    HWMessageBox.Show(this, $"长度有误");
                                }
                                else
                                {
                                    EDataType dataTypeValue = CommonHelper.GetEnumByName(dataType, EDataType.SHORT);

                                    try
                                    {
                                        var modbusHelper = ModbusHelper.CreateRtuModbus(name, portNameValue, baudRateValue, dataBitValue, parityValue, stopBitValue,
                                            (byte)stationValue, dataFormatValue, isStringReserveValue, null, false);

                                        if (modbusHelper.IsConnected)
                                        {
                                            var datas = modbusHelper.Read(addressValue, lengthValue, dataTypeValue.ToString().ToLower());
                                            if (datas != null && datas.Count > 0)
                                            {
                                                HWMessageBox.Show(this, $"结果：{string.Join(",", datas)}");
                                            }
                                            else
                                            {
                                                HWMessageBox.Show(this, "通讯异常");
                                            }
                                            modbusHelper.Close();

                                        }
                                        else
                                        {
                                            HWMessageBox.Show(this, "无法连接");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    HWMessageBox.Show(this, "名称有误");
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录");
            }
            CommonHelper.CloseWaiting();
        }

        private void buttonMaxSize_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }
        }

        private void FormModbus_Shown(object sender, EventArgs e)
        {
        }

        private void dataGridViewTcp_SelectionChanged(object sender, EventArgs e)
        {
            if (!this.mIsFirstTimeSelected)
            {
                SaveModules();

                int selectedRowIndex = this.dataGridViewTcp.SelectedCells == null || this.dataGridViewTcp.SelectedCells.Count == 0 ? -1 : this.dataGridViewTcp.SelectedCells[0].RowIndex;
                if (selectedRowIndex != -1)
                {
                    DataGridViewRow row = this.dataGridViewTcp.Rows[selectedRowIndex];
                    var name = CommonHelper.GetCellStringValue(row, "Name");
                    var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                    var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                    var station = CommonHelper.GetCellStringValue(row, "Station");
                    var dataFormat = CommonHelper.GetCellStringValue(row, "DataFormat");
                    var isStringReserve = CommonHelper.GetCellStringValue(row, "IsStringReserve");

                    int portValue = 502;
                    ModbusEntity m = new ModbusEntity()
                    {
                        Name = name,
                        CommunicationType = ECommunicationType.MODBUS_TCP,
                        TcpEntity = new TcpEntity()
                        {
                            IP = ip,
                            Port = int.TryParse(port, out portValue) ? portValue : 502
                        },
                        Station = string.IsNullOrWhiteSpace(station) ? (byte)0x01 : (byte)int.Parse(station),
                        Format = CommonHelper.GetEnumByName(dataFormat, EDataFormat.ABCD),
                        IsStringReserve = string.IsNullOrWhiteSpace(isStringReserve) ? false : bool.Parse(isStringReserve)
                    };
                    if (row.Tag != null)
                    {
                        ModbusEntity cm = row.Tag as ModbusEntity;
                        m.AddressList = cm.AddressList;
                    }
                    row.Tag = m;

                    ShowModules(m.AddressList);

                    this.mSerialLastSelectedRowIndex = -1;
                    this.mTcpLastSelectedRowIndex = selectedRowIndex;
                }
            }
            this.mIsFirstTimeSelected = false;
        }

        private void dataGridViewRtu_SelectionChanged(object sender, EventArgs e)
        {
            if (!this.mIsFirstTimeSelected)
            {
                SaveModules();

                int selectedRowIndex = this.dataGridViewRtu.SelectedCells == null || this.dataGridViewRtu.SelectedCells.Count == 0 ? -1 : this.dataGridViewRtu.SelectedCells[0].RowIndex;
                if (selectedRowIndex != -1)
                {
                    DataGridViewRow row = this.dataGridViewRtu.Rows[selectedRowIndex];

                    var name = CommonHelper.GetCellStringValue(row, "Name");
                    var station = CommonHelper.GetCellStringValue(row, "Station");
                    var dataFormat = CommonHelper.GetCellStringValue(row, "DataFormat");
                    var isStringReserve = CommonHelper.GetCellStringValue(row, "IsStringReserve");
                    var portName = CommonHelper.GetCellStringValue(row, "PortName");
                    var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                    var parity = CommonHelper.GetCellStringValue(row, "Parity");
                    var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                    var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");

                    ModbusEntity m = new ModbusEntity()
                    {
                        Name = name,
                        CommunicationType = ECommunicationType.MODBUS_RTU,
                        SerialEntity = new SerialEntity
                        {
                            BaudRate = string.IsNullOrWhiteSpace(baudRate) ? 9600 : int.Parse(baudRate),
                            DataBit = string.IsNullOrWhiteSpace(dataBit) ? 9600 : int.Parse(dataBit),
                            ParityBit = string.IsNullOrWhiteSpace(parity) ? 9600 : int.Parse(parity),
                            StopBit = string.IsNullOrWhiteSpace(stopBit) ? 9600 : int.Parse(stopBit),
                            PortName = portName,
                        },
                        Station = string.IsNullOrWhiteSpace(station) ? (byte)0x01 : (byte)int.Parse(station),
                        Format = CommonHelper.GetEnumByName(dataFormat, EDataFormat.ABCD),
                        IsStringReserve = string.IsNullOrWhiteSpace(isStringReserve) ? false : bool.Parse(isStringReserve)
                    };
                    if (row.Tag != null)
                    {
                        ModbusEntity cm = row.Tag as ModbusEntity;
                        m.AddressList = cm.AddressList;
                    }
                    row.Tag = m;

                    ShowModules(m.AddressList);

                    this.mTcpLastSelectedRowIndex = -1;
                    this.mSerialLastSelectedRowIndex = selectedRowIndex;
                }
            }
            this.mIsFirstTimeSelected = false;
        }
        private void SaveModules()
        {
            List<ModbusPositionEntity> list = new List<ModbusPositionEntity>();
            if (this.dataGridViewModules.Rows != null && this.dataGridViewModules.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in this.dataGridViewModules.Rows)
                {
                    var name = CommonHelper.GetCellStringValue(row, "Name");
                    var address = CommonHelper.GetCellStringValue(row, "Address");
                    var dataType = CommonHelper.GetCellStringValue(row, "DataType");
                    var targetDataType = CommonHelper.GetCellStringValue(row, "TargetDataType");
                    var isNumberConvert = CommonHelper.GetCellStringValue(row, "IsNumberConvert");
                    var pLCAddress = CommonHelper.GetCellStringValue(row, "PLCAddress");
                    var remark = CommonHelper.GetCellStringValue(row, "Remark");

                    var p = new ModbusPositionEntity()
                    {
                        Name = name,
                        Address = string.IsNullOrWhiteSpace(address) ? -1 : int.Parse(address),
                        DataType = string.IsNullOrWhiteSpace(dataType) ? EDataType.SHORT : CommonHelper.GetEnumByName(dataType, EDataType.SHORT),
                        TargetDataType = string.IsNullOrWhiteSpace(targetDataType) ? EDataType.SHORT : CommonHelper.GetEnumByName(targetDataType, EDataType.SHORT),
                        Remark = remark,
                        PLCAddress = pLCAddress,
                        IsNumberConvert = string.IsNullOrWhiteSpace(isNumberConvert) ? false : bool.Parse(isNumberConvert),
                    };
                    if (!string.IsNullOrWhiteSpace(p.Name) && p.Address != -1)
                    {
                        list.Add(p);
                    }
                }
            }
            if (this.mTcpLastSelectedRowIndex != -1)
            {
                var tcpRow = this.dataGridViewTcp.Rows[this.mTcpLastSelectedRowIndex];
                if (tcpRow != null && tcpRow.Tag != null)
                {
                    ModbusEntity t = tcpRow.Tag as ModbusEntity;
                    foreach (var m in list)
                    {
                        m.Category = t.Name;
                    }
                    t.AddressList = list;
                    tcpRow.Tag = t;
                }
            }
            else if (this.mSerialLastSelectedRowIndex != -1)
            {
                var serialRow = this.dataGridViewRtu.Rows[this.mSerialLastSelectedRowIndex];
                if (serialRow != null && serialRow.Tag != null)
                {
                    ModbusEntity t = serialRow.Tag as ModbusEntity;

                    foreach (var m in list)
                    {
                        m.Category = t.Name;
                    }
                    t.AddressList = list;
                    serialRow.Tag = t;
                }
            }
        }

        private void ShowModules(List<ModbusPositionEntity> list)
        {
            this.dataGridViewModules.Rows.Clear();
            if (list != null && list.Count > 0)
            {
                foreach (var l in list)
                {
                    int index = this.dataGridViewModules.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewModules.Rows[index];

                    newRow.Cells["Name"].Value = l.Name;
                    newRow.Cells["Address"].Value = l.Address;
                    newRow.Cells["DataType"].Value = l.DataType.ToString();
                    newRow.Cells["TargetDataType"].Value = l.TargetDataType.ToString();
                    newRow.Cells["IsNumberConvert"].Value = l.IsNumberConvert;
                    newRow.Cells["PLCAddress"].Value = l.PLCAddress;
                    newRow.Cells["Remark"].Value = l.Remark;
                }
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = tabControl1.SelectedIndex;

            if (index == 0)
            {
                this.dataGridViewTcp.Rows[0].Cells[0].Selected = true;
            }
            else if (index == 1)
            {
                this.dataGridViewRtu.Rows[0].Cells[0].Selected = true;
            }
        }

        private void dataGridViewModules_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex.Equals(this.dataGridViewRtu.Columns.IndexOf(dataTypeModulesColumn))
                || e.ColumnIndex.Equals(this.dataGridViewRtu.Columns.IndexOf(targetDataTypeModulesColumn)))
            {
                SendKeys.Send("{F4}");
            }
        }

        private void dataGridViewModules_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            var dataTypeCell = e.Row.Cells["DataType"] as DataGridViewComboBoxCell;
            if (dataTypeCell != null)
            {
                dataTypeCell.Value = EDataType.SHORT.ToString();
            }
            var targetDataTypeCell = e.Row.Cells["TargetDataType"] as DataGridViewComboBoxCell;
            if (targetDataTypeCell != null)
            {
                targetDataTypeCell.Value = EDataType.SHORT.ToString();
            }
        }
    }
}
